<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>教师管理</el-breadcrumb-item>
      <el-breadcrumb-item>教师信息</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区-->
    <el-card>
      <!--搜索与添加-->
      <el-row :gutter="10">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" clearable @clear="getTeacherList">
            <el-select v-model="select" slot="prepend" placeholder="请选择">
              <el-option label="学院编号" :value="1"></el-option>
              <el-option label="姓名" :value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="selectTeacherByQuery"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true" >添加教师</el-button>
        </el-col>
      </el-row>
      <!--学院列表区域-->
      <el-table :data="teacherList" class="tableBox" border stripe>
        <el-table-column  align="center" label="序号" type="index"></el-table-column>
        <el-table-column  align="center" label="学院编号" prop="campusId"></el-table-column>
        <el-table-column  align="center" label="姓名" prop="teacherName"></el-table-column>
        <el-table-column  align="center" label="教师编号" prop="teacherId"></el-table-column>
        <el-table-column  align="center" label="性别" prop="gender"></el-table-column>
        <el-table-column  align="center" label="电话号码" prop="tel"></el-table-column>
        <el-table-column  align="center" label="负责人">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.principal"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="是"
              inactive-text="否"
              @change="principalChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column  align="center" label="操作" width="160px">
          <template slot-scope="scope">
            <!--修改-->
            <el-button type="primary" icon="el-icon-edit" circle @click="showEditDialog(scope.row.teacherId)"></el-button>
            <!--删除-->
            <el-button type="danger" icon="el-icon-delete" circle @click="removeTeacherById(scope.row.teacherId)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[20, 40, 60, 80]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!--添加学院的对话框-->
      <el-dialog
        title="添加教师"
        :visible.sync="addDialogVisible"
        @close="addDialogClosed"
        width="30%">
        <!--内容主体区域-->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
          <el-form-item label="学院编号" prop="campusId">
            <el-select v-model="addForm.campusId" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in campuses"
                :key="item.id"
                :label="item.id"
                :value="item.id">
                <span style="float: left">{{ item.id }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
              </el-option>
            </el-select>
        </el-form-item>
          <el-form-item label="姓名" prop="teacherName">
            <el-input v-model="addForm.teacherName"></el-input>
          </el-form-item>
          <el-form-item label="教师编号" prop="teacherId">
            <el-input v-model="addForm.teacherId"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="principal">
            <el-radio-group v-model="addForm.gender">
              <el-radio-button label="男">男</el-radio-button>
              <el-radio-button label="女">女</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="电话号码" prop="tel">
            <el-input v-model="addForm.tel"></el-input>
          </el-form-item>
          <el-form-item label="负责人" prop="principal">
            <el-radio-group v-model="addForm.principal">
              <el-radio-button :label="true">是</el-radio-button>
              <el-radio-button :label="false">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <!--底部区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addTeacher">确 定</el-button>
        </span>
      </el-dialog>

      <!--修改用户的对话框-->
      <el-dialog
        title="修改教师"
        :visible.sync="editDialogVisible"
        width="30%"
        @close="editDialogClosed">
        <!--内容主体区域-->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" >
          <el-form-item label="学院编号" prop="campusId">
            <el-select v-model="editForm.campusId" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in campuses"
                :key="item.id"
                :label="item.id"
                :value="item.id">
                <span style="float: left">{{ item.id }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="姓名" prop="teacherName">
            <el-input v-model="editForm.teacherName"></el-input>
          </el-form-item>
          <el-form-item label="教师编号" prop="teacherId">
            <el-input v-model="editForm.teacherId" disabled></el-input>
          </el-form-item>
          <el-form-item label="负责人" prop="principal">
            <el-radio-group v-model="editForm.gender">
              <el-radio-button label="男">男</el-radio-button>
              <el-radio-button label="女">女</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="电话号码" prop="tel">
            <el-input v-model="editForm.tel"></el-input>
          </el-form-item>
<!--          <el-form-item label="负责人" prop="principal">-->
<!--            <el-radio-group v-model="editForm.principal">-->
<!--              <el-radio-button :label="true">是</el-radio-button>-->
<!--              <el-radio-button :label="false">否</el-radio-button>-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editTeacher">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>export default {
  data () {
    return {
      select: '',
      campuses: [],
      //  获取用户列表参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      teacherList: [],
      total: 0,
      //  控制对话的显示
      addDialogVisible: false,
      //  添加用户的表单数据
      addForm: {
        teacherName: '',
        teacherId: '',
        campusId: '',
        gender: '',
        tel: '',
        principal: ''
      },
      //  添加表单的验证规则对象
      addFormRules: {
        teacherName: [
          { required: true, message: '请输入学院名称', trigger: 'blur' }
        ],
        teacherId: [
          { required: true, message: '请输入教师编号', trigger: 'blur' }
        ],
        campusId: [
          { required: true, message: '请输入学院编号', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请输入性别', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入电话号码', trigger: 'blur' }
        ],
        principal: [
          { required: true, message: '请选择教师类型', trigger: 'change' }
        ]
      },
      //  修改表单的验证规则对象
      editFormRules: {
        teacherName: [
          { required: true, message: '请输入学院名称', trigger: 'blur' }
        ],
        teacherId: [
          { required: true, message: '请输入教师编号', trigger: 'blur' }
        ],
        campusId: [
          { required: true, message: '请输入学院编号', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请输入性别', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入电话号码', trigger: 'blur' }
        ],
        principal: [
          { required: true, message: '请选择教师类型', trigger: 'change' }
        ]
      },
      //  控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      //  查询到的用户信息对象
      editForm: {
        teacherName: '',
        teacherId: '',
        campusId: '',
        gender: '',
        tel: '',
        principal: ''
      }
    }
  },
  created () {
    this.getCampusList()
    this.getTeacherList()
  },
  methods: {
    async selectTeacherByQuery () {
      if (this.queryInfo.query === '') {
        return this.$message.error('请输入查询数据')
      }
      if (this.select === 1) {
        const {data: res} = await this.$http.get(`/teacher/findByCampusIdEquals?campusId=${this.queryInfo.query}`)
        if (res.code !== 200 || res.data.length === 0) {
          return this.$message.error('查询失败')
        }
        this.teacherList = res.data.filter(n => n).sort(
          function (a, b) {
            return a.teacherId > b.teacherId ? 1 : -1
          }
        )
        this.total = res.data.length
      } else if (this.select === 2) {
        const {data: res} = await this.$http.get(`/teacher/findByTeacherNameContains?teacherName=${this.queryInfo.query}`)
        if (res.code !== 200) {
          return this.$message.error('查询失败')
        }
        this.teacherList = res.data.filter(n => n).sort(
          function (a, b) {
            return a.teacherId > b.teacherId ? 1 : -1
          }
        )
        this.total = res.data.length
      } else {
        return this.$message.error('请选择查询条件')
      }
    },
    async principalChange (info) {
      const { data: campus } = await this.$http.get(`/campus/findByCampusIdEquals?campusId=${info.campusId}`)
      if (campus.data.administrator === info.teacherName && info.principal === false) {
        info.principal = true
        return this.$message.error('每个学院必须有一位负责人!')
      }
      //  可以发起修改用户的网络请求
      const {data: res} = await this.$http.post('teacher/update', info)
      if (res.code !== 200) {
        return this.$message.error('修改教师信息失败！')
      }
      this.$message.success('修改教师信息成功!')
      //  重新获取用户列表数据
      await this.getTeacherList()
    },
    //  获取学院列表 并排序
    async getCampusList () {
      this.campuses = []
      let result
      const { data: res } = await this.$http.get('/campus/findAll')
      if (res.code !== 200) {
        return this.$message.error('获取学院列表失败')
      }
      result = res.data.filter(n => n).sort(
        function (a, b) {
          return a.campusId > b.campusId ? 1 : -1
        }
      )
      //  通过学院号查找教师id
      for (let i = 0; i < result.length; i++) {
        let book = []
        const { data: res } = await this.$http.get(`/teacher/findByCampusIdEquals?campusId=${result[i].campusId}`)
        for (let j = 0; j < res.data.length; j++) {
          const { data: res2 } = await this.$http.get(`/book/findByTeacherId?teacherId=${res.data[j].teacherId}`)
          res2.data.forEach(e => book.push(e))
        }
        this.campuses.push({
          key: i,
          name: result[i].campusName,
          id: result[i].campusId,
          book: book
        })
      }
    },
    //  获取教师列表
    async getTeacherList () {
      const { data: res } = await this.$http.get('/teacher/findAll')
      if (res.code !== 200) {
        return this.$message.error('获取教师列表失败')
      }
      this.teacherList = res.data.filter(n => n).sort(
        function (a, b) {
          return a.teacherId > b.teacherId ? 1 : -1
        }
      )
      this.total = res.data.length
    },
    //  监听Pagesize
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getTeacherList()
    },
    // 监听页码值改变
    handleCurrentChange (newPage) {
      this.queryInfo.pagesize = newPage
      this.getTeacherList()
    },
    //  监听添加用户对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    //  监听修改用户对话框的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    //  点击按钮添加新用户
    addTeacher () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        //  可以发起添加用户的网络请求
        const {data: res} = await this.$http.post('/teacher/insert', this.addForm)
        if (res.code !== 200) {
          return this.$message.error('添加教师失败！')
        }
        this.$message.success('添加教师成功!')
        //  隐藏添加用户的对话框
        this.addDialogVisible = false
        //  重新获取用户列表数据
        this.getTeacherList()
      })
    },
    //  展示编辑用户的对话框
    async showEditDialog (id) {
      const {data: res} = await this.$http.get(`teacher/findByTeacherIdEquals?teacherId=${id}`)
      if (res.code !== 200) {
        return this.$message.error('获取教师信息失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    //  修改用户信息并提交
    editTeacher () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        //  可以发起修改用户的网络请求
        const {data: res} = await this.$http.post('teacher/update', this.editForm)
        if (res.code !== 200) {
          return this.$message.error('修改教师信息失败！')
        }
        this.$message.success('修改教师信息成功!')
        //  隐藏添加用户的对话框
        this.editDialogVisible = false
        //  重新获取用户列表数据
        this.getTeacherList()
      })
    },
    //  根据id删除对应的用户信息
    async removeTeacherById (id) {
      //  弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.get(`teacher/delete?teacherId=${id}`)
      if (res.code !== 200) {
        return this.$message.error('删除教师失败！')
      }
      this.$message.success('删除教师成功！')
      this.getTeacherList()
    }
  }
}
</script>

<style lang="less" scoped>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .el-select {
    width: 130px !important;
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
</style>
